<template>
  <div class="attractionsBox">
    <div class="top">
      <el-button @click="deal(0, null)" style="margin-right: 20px" type="primary" :icon="Plus">
        新建
      </el-button>
      <!-- <el-select
        v-model="statusValue"
        placeholder="选择状态"
        size="large"
        style="width: 200px"
      >
        <el-option label="正常" value="1"> </el-option>
        <el-option label="已禁用" value="0"> </el-option>
      </el-select> -->
    </div>
    <div class="bottom">
      <el-table stripe :data="tableData" size="large" style="width: calc(100vw - 300px)">
        <!-- <el-table-column label="id" prop="id" /> -->
        <el-table-column label="游客姓名" prop="touristName" />
        <el-table-column label="游客手机号" prop="phoneNum" />
        <el-table-column label="行程线路名称" prop="routeName" />
        <el-table-column label="行程天数" prop="travelDays" />
        <el-table-column label="创建人" prop="creater" />

        <el-table-column label="操作" fixed="right" min-width="340">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" plain @click="handleEdit(scope.$index, scope.row)">
              查看
            </el-button>
            <el-button type="info" :icon="Edit" plain @click="handleEdit(scope.$index, scope.row)" v-if="
              userStore.getUser() !== null &&
              userStore.getUser()!.roles === 'admin'
            ">
              编辑
            </el-button>

            <el-button type="danger" :icon="Delete" plain @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination @prev-click="getTouristRoute(touristRoutePageData.current - 1)"
          @next-click="getTouristRoute(touristRoutePageData.current + 1)" @current-change="getTouristRoute"
          layout="prev, pager, next" :total="touristRoutePageData.total" />
      </div>
    </div>
  </div>

  <el-dialog v-model="outerVisible" :title="modalTitle" width="80%" style="min-width: 800px" top="80px">
    <div class="touristBox" style="width:100%;display: flex;">
      <el-form :model="form" :rules="rules" ref="form4" style="flex:1;display: flex;margin-right:20px;">
        <el-form-item style="flex:1;" label='游客姓名' prop="touristName">
          <el-input v-model="form.touristName"></el-input>
        </el-form-item>
      </el-form>

      <el-form :model="form" :rules="rules" ref="form5" style="flex:1;display: flex;margin-right:20px;">
        <el-form-item style="flex:1;" label='游客手机号' prop="phoneNum">
          <el-input v-model="form.phoneNum"></el-input>
        </el-form-item>
      </el-form>


      <el-form-item style="flex:1;opacity:0;">
        <el-input disabled></el-input>
      </el-form-item>
      <!-- <el-input v-show='false'></el-input> -->
    </div>
    <div class="infoBox">
      <div class="firstBox">
        <el-form :model="form" ref="form1" :rules="rules" status-icon label-width="auto">
          <el-form-item label="出发地点" prop="departureLocation">
            <el-input v-model="form.departureLocation" autocomplete="off" />
          </el-form-item>
          <el-form-item label="返回地点" prop="returnLocation">
            <el-input v-model="form.returnLocation" />
          </el-form-item>
          <el-form-item label="线路名称" prop="routeName">
            <el-input v-model="form.routeName" autocomplete="off" />
          </el-form-item>
        </el-form>
      </div>
      <div class="secondBox">
        <el-form status-icon ref="form2" :model="form" :rules="rules" label-width="auto">
          <el-form-item label="出发时间" prop="departureTime" style='display:flex'>
            <el-date-picker type="datetime" v-model="form.departureTime" style="flex:1;" />
          </el-form-item>
          <el-form-item label="返回时间" prop="returnTime" style='display:flex'>
            <el-date-picker type="datetime" v-model="form.returnTime" style="flex:1;" />
          </el-form-item>
        </el-form>
      </div>
      <div class="thirdBox">
        <el-form status-icon ref="form3" :model="form" :rules="rules" label-width="auto">
          <el-form-item label="交通工具" prop="departureVehicle">
            <el-select v-model="form.departureVehicle">
              <el-option label="汽车" value="汽车"></el-option>
              <el-option label="火车" value="火车"></el-option>
              <el-option label="飞机" value="飞机"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交通工具" prop="returnVehicle">
            <el-select v-model="form.returnVehicle">
              <el-option label="汽车" value="汽车"></el-option>
              <el-option label="火车" value="火车"></el-option>
              <el-option label="飞机" value="飞机"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="行程天数" prop="travelDays">
            <el-input v-model="form.travelDays" autocomplete="off" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <hr />
    <h4 style="margin-top: 20px">行程信息</h4>
    <el-button type="primary" @click="addItinerary" style="margin-top: 10px" :icon="Plus">新建</el-button>
    <div class="infoDetailsBox">
      <el-table stripe :data="form.travelInformations" size="large" style="width: 100%">
        <el-table-column label="日期">
          <template #default="scope">
            {{ "第" + `${scope.$index + 1}` + "天" }}
          </template>
        </el-table-column>

        <el-table-column label="前往地" prop="destination">
          <template #default="scope">
            <el-input v-model="scope.row.destination" type="textarea" />
          </template>
        </el-table-column>
        <el-table-column label="行程安排及浏览景点" prop="travelDate">
          <template #default="scope">
            <el-input :value="scope.row.travelScenicInformations
              .map((scenicSpotItem) => scenicSpotItem.scenicSpot.name)
              .join('+')
              " @click="
                dealSecondModal(
                  0,
                  scope.$index,
                  scope.row.travelScenicInformations
                )
                " type="textarea" style="" />
          </template>
        </el-table-column>
        <el-table-column label="入住酒店" prop="hotelAccomodation">
          <template #default="scope">
            <el-input @click="
              dealSecondModal(1, scope.$index, scope.row.hotelAccomodation)
              " v-model="scope.row.hotelAccomodation" type="textarea" />
          </template>
        </el-table-column>
        <el-table-column label="文化演艺" prop="theatricalPerformance">
          <template #default="scope">
            <el-input v-model="scope.row.theatricalPerformance" @click="dealSecondModal(2, scope.$index)"
              type="textarea" />
          </template>
        </el-table-column>
        <el-table-column label="交通工具">
          <template #default="scope">
            <el-select v-model="scope.row.vehicle">
              <el-option label="奔驰7座" value="奔驰7座"></el-option>
              <el-option label="别克" value="别克"></el-option>
              <el-option label="九座商务车" value="九座商务车"></el-option>
              <el-option label="18座大巴车" value="18座大巴车"></el-option>
              <el-option label="的士" value="的士"></el-option>
              <el-option label="私家车" value="私家车"></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="deleteTourist(scope.$index, scope.row.id)" type="danger" :icon="Delete" circle />
            <!-- <el-button @click="saveTourist(scope.row.id)" type="success" :icon="Check" circle />  -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="innerVisible" width="80%" stripe :title="modalSecondTitle" append-to-body>
      <div class="plan" v-if="modalSecondTitle === '行程安排及浏览景点'">
        <el-cascader placeholder="输入您的安排" :options="options" v-model="itineraryValue" @change="addNewItinerary"
          filterable />
        <el-table :data="scenicSpotsList" size="large" style="width: 100%">
          <el-table-column label="序号" type="index" min-width="100px" />

          <el-table-column label="名称" prop="scenicSpot.name" />

          <el-table-column label="操作" fixed="right" width="320">
            <template #default="scope">
              <el-button v-if="scope.$index !== 0" size="mid" type="primary" text="plain" plain :icon="ArrowUp"
                @click="upEdit(scope.$index, scope.row)">
                上移
              </el-button>
              <el-button v-if="scope.$index !== scenicSpotsList.length - 1" type="primary" size="mid" plain text="plain"
                :icon="ArrowDown" @click="downEdit(scope.$index, scope.row)">
                下移
              </el-button>
              <el-button type="danger" size="mid" plain text="plain" :icon="Delete"
                @click="deleteScenicSpot(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="modalSecondTitle === '文化演艺'" class="cultureBox">
        <div class="top" style="display: flex">
          <el-button type="primary" :icon="Plus" @click="toDealThirdModal(1)">添加</el-button>
        </div>
        <el-table v-if="currentCultureRow != null && currentCultureRow.id !== null" :data="[1]"
          style="margin-top: 20px; margin-bottom: 40px">
          <el-table-column label="您的选择">
            <template #default></template>
          </el-table-column>
          <el-table-column label="名称">
            <template #default>{{ currentCultureRow.name }}</template>
          </el-table-column>
          <el-table-column label="区域" prop="region">
            <template #default>{{
              currentCultureRow.region
            }}</template></el-table-column>
          <el-table-column label="地址" prop="address">
            <template #default>{{ currentCultureRow.address }}</template>
          </el-table-column>
        </el-table>

        <el-table ref="cultureTableRef" :data="cultures" highlight-current-row @current-change="handleCultureChange">
          <el-table-column label="">
            <template #default="scope">
              <el-checkbox v-if="currentCultureRow.name === scope.row.name" @change="toSetCurrentCulture(scope.row)"
                :checked="true" size="large" />
              <el-checkbox v-else @change="toSetCurrentHotel(scope.row)" :checked="false" size="large" />
            </template>
          </el-table-column>

          <!-- <el-table-column type="index" width="50" /> -->
          <el-table-column label="名称" prop="name" />
          <el-table-column label="区域" prop="region" />
          <el-table-column label="地址" prop="address" />
        </el-table>
        <el-pagination style="margin-top: 20px" layout="prev, pager, next" @current-change="getAllCulture"
          @prev-click="getAllCulture" @next-click="getAllCulture" :total="culturePageData.total" />
      </div>

      <div v-else class="hotelBox">
        <el-input :prefix-icon="Search" style="width: 200px" placeholder="请输入你想搜索的酒店" @keyup.enter="getAllHotels"
          v-model="hotelName" ref="addHotelRef"></el-input>

        <el-button @click="getAllHotels" type="primary">搜索</el-button>
        <el-button type="primary" style="margin-left: 20px" :icon="Plus" @click="toDealThirdModal(0)">添加</el-button>

        <br />

        <el-table v-if="currentHotelRow.id !== null" :data="[1]" style="margin-top: 20px; margin-bottom: 40px">
          <el-table-column label="您的选择">
            <template #default></template>
          </el-table-column>
          <el-table-column label="区域">
            <template #default>
              {{ currentHotelRow.region }}
            </template>
          </el-table-column>
          <el-table-column label="酒店名称">
            <template #default>{{ currentHotelRow.hotelName }}</template>
          </el-table-column>
          <el-table-column label="酒店星级">
            <template #default>{{ currentHotelRow.starLevel }}</template>
          </el-table-column>
          <el-table-column label="酒店地址">
            <template #default>{{ currentHotelRow.position }}</template>
          </el-table-column>
        </el-table>

        <el-table ref="hotelTableRef" :data="hotels" highlight-current-row @current-change="handleHotelChange">
          <el-table-column label="酒店地址">
            <template #default="scope">
              <el-checkbox v-if="currentHotelRow.id === scope.row.id" @change="toSetCurrentHotel(scope.row)"
                :checked="true" size="large" />
              <el-checkbox v-else @change="toSetCurrentHotel(scope.row)" :checked="false" size="large" />
            </template>
          </el-table-column>

          <!-- <el-table-column type="index" width="50" /> -->
          <el-table-column label="区域" prop="region" />
          <el-table-column label="酒店名称" prop="hotelName" />
          <el-table-column label="酒店星级" prop="starLevel" />
          <el-table-column label="酒店地址" prop="position" />
        </el-table>
        <el-pagination style="margin-top: 20px" layout="prev, pager, next" @current-change="getAllHotels" :page-size="5"
          :total="hotelPageData.total" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="innerVisible = false">取消</el-button>
          <el-button type="primary" @click="toDealCloseSecondModal">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="outerVisible = false">取消</el-button>
        <el-button type="primary" @click="dealFirstModal"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="thirdModalVisible" :title="thirdModalTitle" width="500">
    <el-form v-if="thirdModalTitle === '新建酒店'" :model="addHotelData" label-position="left" label-width="90"
      style="margin-right: 20px" :rules="addHotelRules" ref="addHotelRef">
      <el-form-item label="酒店名称" prop="hotelName">
        <el-input v-model="addHotelData.hotelName" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input type="number" v-model="addHotelData.price" />
      </el-form-item>

      <el-form-item label="星级" prop="starLevel">
        <el-input type="number" min="1" max="5" v-model="addHotelData.starLevel" />
      </el-form-item>

      <el-form-item label="位置" prop="position">
        <el-input v-model="addHotelData.position" />
      </el-form-item>

      <el-form-item label="区域" prop="region">
        <el-input v-model="addHotelData.region" />
      </el-form-item>
    </el-form>

    <el-form v-else :model="addCultureData" label-position="left" label-width="90" style="margin-right: 20px"
      :rules="addCultureRules" ref="addCultureRef">
      <el-form-item label="区域" prop="region">
        <el-input v-model="addCultureData.region" />
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input v-model="addCultureData.name" />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input v-model="addCultureData.address" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="thirdModalVisible = false">取消</el-button>
        <el-button type="primary" @click="toAddThirdModal"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, reactive } from "vue";
import {
  Plus,
  Edit,
  Delete,
  Search,
  ArrowUp,
  ArrowDown,
} from "@element-plus/icons-vue";
import {
  addTouristRouteAPI,
  deleteTouristRouteAPI,
  getAllTouristAPI,
  updateTouristRouteAPI,
} from "../../apis/touristRouter";
import { ElMessage, FormRules, FormInstance } from "element-plus";
import { ElTable } from "element-plus";
import { getHotelByPageAPI, addHotelAPI } from "../../apis/hotel";
import { getCityAPI } from "../../apis/city";
import { searchSingleScenicSpotAPI } from "../../apis/scenicSpot";
import { useUserStore } from "../../stores/userStore";
import { getArtShowByPageAPI } from "@/apis/artShow";
import { addArtShowAPI } from "../../apis/artShow";

const userStore = useUserStore();
const currentHotelRow = ref({
  id: null,
  hotelName: "",
  price: 120,
  starLevel: 1,
  position: "",
  region: "",
});
const currentCultureRow = ref({
  id: null,
  name: "",
  region: "",
  address: "",
});

const hotelTableRef = ref<InstanceType<typeof ElTable>>();
const cultureTableRef = ref<InstanceType<typeof ElTable>>();
const outerVisible = ref(false);
const innerVisible = ref(false);
const hotelName = ref("");

const form1 = ref<FormInstance>();
const form2 = ref<FormInstance>();
const form3 = ref<FormInstance>();

const hotelPageData = ref({
  current: 1,
  total: 0,
});

const touristRoutePageData = ref({
  current: 1,
  total: 0,
});

// 新建行程 或者 编辑行程
const modalTitle = ref("新建行程");

// 行程安排及浏览景点 以及 文化演艺
const modalSecondTitle = ref("行程安排及浏览景点");

const form = ref<Itinerary>({
  id: "",
  touristName: "",
  phoneNum: "",
  routeName: "",
  travelDays: 0,
  departureLocation: "",
  departureTime: "",
  departureVehicle: "",
  returnLocation: "",
  returnTime: "",
  returnVehicle: "",
  creater: "",
  travelInformations: [
    {
      id: "",
      travelDate: "第一天",
      destination: "",
      hotelAccomodation: "",
      theatricalPerformance: "",
      price: 0,
      touristRouteId: "",
      order: 1,
      vehicle: "的士",
      travelScenicInformations: [],
    },
  ],
});

const culturePerformingArts = ref([]);

const currentScenicSpotsIndex = ref(0);
const scenicSpotsList = ref([]);
const hotels = ref([]);

const statusValue = ref();

const handleHotelChange = (val: any) => {
  currentHotelRow.value = val;
};

const handleCultureChange = (val: any) => {
  currentCultureRow.value = val;
};

interface Itinerary {
  id: string;
  touristName: string;
  phoneNum: string;
  routeName: string;
  travelDays: number;
  departureLocation: string;
  departureTime: string;
  departureVehicle: string;
  returnLocation: string;
  returnTime: string;
  returnVehicle: string;
  creater: string;
  travelInformations: {
    id: string;
    travelDate: string;
    destination: string;
    hotelAccomodation: string;
    theatricalPerformance: string;
    price: number;
    touristRouteId: string;
    order: number;
    vehicle: string;
    travelScenicInformations: {
      id: string;
      travelInformationId: string;
      scenicSpotId: string;
      scenicSpot: {
        id: string;
        name: string;
        pictureUrl: string;
        description: string;
        price: number;
        belongCity: string;
        cityId: string;
      };
    }[];
  }[];
}

const search = ref("");
const currentRouterIndex = ref(0);

const handleEdit = (index: number, row: Itinerary) => {
  console.log(row);
  currentRouterIndex.value = index;
  deal(1, row);
};

const handleDelete = async (index: number, row: Itinerary) => {
  let flag = confirm("您确定要删除吗？");
  if (flag === false) return;

  const res = await deleteTouristRouteAPI(row.id);

  if (res.data.code === "200") {
    ElMessage.success("删除成功");

    getAllRouters();
  } else {
    ElMessage.error(res.data.message);
  }
};

const tableData = ref<Itinerary[]>();

const getTouristRoute = (page: number) => {
  if (page < 1) return;

  if (page > touristRoutePageData.value.total) return;

  touristRoutePageData.value.current = page;

  getAllRouters();
};

const getAllRouters = async () => {
  const res = await getAllTouristAPI(touristRoutePageData.value.current, 5);

  if (res.data.code === "200") {
    tableData.value = res.data.data.data;
    touristRoutePageData.value.total = res.data.data.total;
  } else ElMessage.error("获取错误");
};

const deal = (flag: number, row: Itinerary) => {
  if (flag === 0) {
    modalTitle.value = "新增";

    form.value = {
      id: "",
      touristName: "",
      phoneNum: "",
      routeName: "",
      travelDays: 0,
      departureLocation: "",
      departureTime: "",
      departureVehicle: "",
      returnLocation: "",
      returnTime: "",
      returnVehicle: "",
      creater: "",
      travelInformations: [],
    };
  } else {
    modalTitle.value = "编辑";

    form.value = row;

    // 排序
    form.value.travelInformations = form.value.travelInformations.sort((a, b) => a.order - b.order);

    console.log(form.value)
  }

  outerVisible.value = true;
};

const form4 = ref<FormInstance>()

const form5 = ref<FormInstance>()

const dealFirstModal = async () => {
  // 表单处理

  let flag1 = await submitForm(form1.value);

  let flag2 = await submitForm(form2.value);

  let flag3 = await submitForm(form3.value);

  let flag4 = await submitForm(form4.value);

  let flag5 = await submitForm(form5.value);
  // let flag4 = 

  if (flag1 === false || flag2 === false || flag3 === false || flag4 === false || flag5 === false) return;


  if (form.value.travelInformations.length <= 0) {
    ElMessage.error("行程至少要有一天");
    return;
  }

  // 处理编辑还是新建
  if (modalTitle.value === "新增") {
    // 新增处理逻辑
    console.log(form.value);

    const res = await addTouristRouteAPI(form.value);

    if (res.data.code === "200") {
      ElMessage.success("新增成功");

      getAllRouters();
    } else return;
  } else {
    // 编辑处理逻辑

    console.log(form.value);

    const res = await updateTouristRouteAPI(form.value);

    if (res.data.code === "200") {
      ElMessage.success("编辑成功");
      getAllRouters();
    } else return;
  }

  outerVisible.value = false;
};

const dealSecondModal = (flag: number, index?: number, data?: any) => {
  if (flag === 0) {
    modalSecondTitle.value = "行程安排及浏览景点";
    //
    console.log(data);
    currentScenicSpotsIndex.value = index;
    scenicSpotsList.value = data;

    console.log(scenicSpotsList.value);

    console.log(currentScenicSpotsIndex.value);

    getCity();
  } else if (flag === 2) {
    modalSecondTitle.value = "文化演艺";

    getAllCulture();
  } else {
    modalSecondTitle.value = "入住酒店";

    hotelName.value = data;
    getAllHotels();
  }

  innerVisible.value = true;
};

const getHotels = (value: number) => {
  hotelPageData.value.current = value;

  getAllHotels();
};

const toSetCurrentHotel = (data: any) => {
  if (currentCultureRow.value.id === null) {
    currentCultureRow.value = data;

    return;
  }

  console.log(data);
  console.log(currentCultureRow.value);

  if (data.id === currentCultureRow.value?.id) {
  } else {
    currentCultureRow.value = data;
  }
};

const getAllHotels = async () => {
  const res = await getHotelByPageAPI(
    hotelPageData.value.current,
    5,
    hotelName.value
  );

  if (res.data.code === "200") {
    hotels.value = res.data.data.data;

    hotelPageData.value.total = res.data.data.total;

    hotelTableRef.value!.setCurrentRow(hotels.value[0]);
  } else {
    ElMessage.error(res.data.message);
  }
};

const cultures = ref([]);

const culturePageData = ref({
  current: 1,
  total: 0,
});

const toSetCurrentCulture = (data: any) => {
  if (data.id === currentCultureRow.value?.id) {
  } else {
    currentHotelRow.value = data;
  }
};

// 获取所有文化演绎
const getAllCulture = async () => {
  const res = await getArtShowByPageAPI(culturePageData.value.current, 5);

  if (res.data.code === "200") {
    cultures.value = res.data.data.data;
    culturePageData.value.total = res.data.data.total;
  } else {
    ElMessage.error(res.data.message);
  }
};

const itineraryValue = ref([]);

const options = ref([
  {
    value: "guide",
    label: "张家界市",
    children: [],
  },
  {
    value: "component",
    label: "吉首市",
    children: [],
  },
]);

const getCity = async () => {
  const res = await getCityAPI();

  if (res.data.code === "200") {
    console.log(res.data.data);
    options.value = res.data.data.map((item) => {
      return {
        value: item.id,
        label: item.cityName,
        children: item.scenicSpots.map((littleItem) => {
          return {
            value: littleItem.id,
            label: littleItem.name,
            scenicSpots: {
              ...littleItem,
            },
          };
        }),
      };
    });
  } else ElMessage.error(res.data.message);
};

const addItinerary = () => {
  form.value.travelInformations.push({
    id: "",
    travelDate: "第" + `${form.value.travelInformations.length + 1}` + "天",
    destination: "",
    hotelAccomodation: "",
    theatricalPerformance: "",
    price: 0,
    touristRouteId: "",
    order: form.value.travelInformations.length,
    vehicle: "的士",
    travelScenicInformations: [],
  });
};

const deleteTourist = (index: number, id: string) => {
  let flag = confirm("您确定要删除吗？");
  if (flag === false) return;

  // const res  = await
  console.log(index);
  form.value.travelInformations = form.value.travelInformations.filter(
    (item, i) => {
      return index !== i;
    }
  );

  form.value.travelInformations.forEach((item, index) => {
    item.order = index + 1;
  });

  // saveTourist()
};

const saveTourist = async () => {
  // 获取到form 里面的值即可

  if (modalTitle.value === "新增") {
    const res = await addTouristRouteAPI(form.value);

    if (res.data.code === "200") {
    } else ElMessage.error(res.data.message);
  } else {
    //

    const res = await updateTouristRouteAPI(form.value);

    if (res.data.code === "200") {
    } else {
    }
  }

  outerVisible.value = false;
};

const rules = reactive<FormRules<any>>({
  touristName: [{
    required: true, message: "游客姓名不能为空", trigger: "blur"
  }],
  phoneNum: [{
    required: true, message: "游客手机号不能为空", trigger: "blur"
  }],
  routeName: [{ required: true, message: "不能为空", trigger: "blur" }],
  departureLocation: [
    { required: true, message: "出发地不能为空", trigger: "blur" },
  ],
  returnLocation: [
    { required: true, message: "返回地点不能为空", trigger: "blur" },
  ],
  departureTime: [{ required: true, message: "不能为空", trigger: "change" }],
  returnTime: [{ required: true, message: "不能为空", trigger: "change" }],
  departureVehicle: [
    {
      required: true,
      message: "交通工具不能为空",
      trigger: "change",
    },
  ],
  returnVehicle: [
    {
      required: true,
      message: "交通工具不能为空",
      trigger: "change",
    },
  ],
  travelDays: [
    {
      required: true,
      message: "行程天数不能为空",
      trigger: "blur",
    },
    {
      min: 1,
      message: "不能低于一天",
      trigger: "blur",
    },
  ],
  destination: [
    {
      required: true,
      message: "目的地不能为空",
      trigger: "blur",
    },
  ],
  hotelAccomodation: [
    {
      required: true,
      message: "不能为空",
      trigger: "blur",
    },
  ],
  travelScenicInformations: [
    {
      required: true,
      message: "不能为空",
      trigger: "blur",
    },
  ],
  theatricalPerformance: [
    {
      required: true,
      message: "不能为空",
      trigger: "blur",
    },
  ],
});

const upEdit = (index: number, item: any) => {
  // 上移交换
  let t = item;
  scenicSpotsList.value[index] = scenicSpotsList.value[index - 1];

  scenicSpotsList.value[index - 1] = t;

  form.value.travelInformations[
    currentScenicSpotsIndex.value
  ].travelScenicInformations = scenicSpotsList.value;
};

const downEdit = (index: number, item: any) => {
  // 下移交换
  let t = item;
  scenicSpotsList.value[index] = scenicSpotsList.value[index + 1];
  scenicSpotsList.value[index + 1] = t;

  form.value.travelInformations[
    currentScenicSpotsIndex.value
  ].travelScenicInformations = scenicSpotsList.value;
};

const deleteScenicSpot = (index: number, item: any) => {
  let flag = confirm("您确定要删除吗？");
  if (flag === false) return;

  scenicSpotsList.value = scenicSpotsList.value.filter(
    (scenicItem, scenicIndex) => {
      return index !== scenicIndex;
    }
  );

  console.log(scenicSpotsList.value);

  // form 也需要删除

  form.value.travelInformations[
    currentScenicSpotsIndex.value
  ].travelScenicInformations = scenicSpotsList.value;

  // console.log(form.value.travelInformations[currentScenicSpotsIndex.value].travelScenicInformations)
};

const addNewItinerary = async () => {
  console.log(itineraryValue.value);

  let id = itineraryValue.value[1];
  console.log(id);
  // const list

  // 先判重
  for (let i = 0; i < options.value.length; i++) {
    for (let j = 0; j < options.value[i].children.length; j++) {
      for (let k = 0; k < scenicSpotsList.value.length; k++) {
        if (scenicSpotsList.value[k].scenicSpotId === id) {
          itineraryValue.value = [];

          ElMessage.error("已有该行程");
          return;
        }
      }
    }
  }

  let scenicSpot = null;
  // 查找
  for (let i = 0; i < options.value.length; i++) {
    for (let j = 0; j < options.value[i].children.length; j++) {
      if (options.value[i].children[j].value === id) {
        scenicSpot = options.value[i].children[j].scenicSpots;
      }
    }
  }

  console.log(scenicSpot);

  scenicSpotsList.value.push({
    id: "",
    travelInformationId:
      tableData.value[currentRouterIndex.value].travelInformations[
        currentScenicSpotsIndex.value
      ].id,
    scenicSpotId: scenicSpot.id,
    scenicSpot: scenicSpot,
  });

  form.value.travelInformations[
    currentScenicSpotsIndex.value
  ].travelScenicInformations = scenicSpotsList.value;

  itineraryValue.value = [];
};

const submitForm = async (formEl: FormInstance | undefined) => {
  let flag = false;

  if (!formEl) return flag;

  console.log(formEl);

  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      flag = true;
    } else {
      console.log("error submit!", fields);
    }
  });

  return flag;
};

const toDealCloseSecondModal = () => {
  console.log(currentHotelRow.value);

  if (modalSecondTitle.value === "入住酒店") {
    // 设置到form中
    form.value.travelInformations[
      currentScenicSpotsIndex.value
    ].hotelAccomodation = currentHotelRow.value.hotelName;
  } else if (modalSecondTitle.value === "文化演艺") {
    form.value.travelInformations[
      currentScenicSpotsIndex.value
    ].theatricalPerformance = currentCultureRow.value.name;
  }

  innerVisible.value = false;
};

// 第三个酒店和文化演艺
const thirdModalVisible = ref(false);

const thirdModalTitle = ref("新建酒店");
const addHotelRef = ref<FormInstance>();

const addHotelData = ref({
  id: null,
  hotelName: "",
  price: 0,
  starLevel: 5,
  position: "",
  region: "",
});

const addHotelRules = reactive<FormRules<any>>({
  hotelName: [
    {
      required: true,
      message: "酒店名字不能为空",
      trigger: "change",
    },
  ],
  price: [
    {
      required: true,
      message: "价格不能为空",
      trigger: "change",
    },
    {
      min: 0,
      message: "不能低于0元",
      trigger: "change",
    },
  ],
  starLevel: [
    {
      required: true,
      message: "星级不能为空",
      trigger: "change",
    },
    {
      min: 1,
      max: 5,
      message: "数字必须处于1-5之间",
      trigger: "blur",
    },
  ],
  position: [
    {
      required: true,
      message: "位置不能为空",
      trigger: "change",
    },
  ],
  region: [
    {
      required: true,
      message: "区域不能为空",
      trigger: "change",
    },
  ],
});

const addCultureRef = ref<FormInstance>();

const addCultureData = ref({
  id: null,
  region: "",
  name: "",
  address: "",
});

const addCultureRules = reactive<FormRules<any>>({
  region: [
    {
      required: true,
      message: "区域名字不能为空",
      trigger: "change",
    },
  ],
  name: [
    {
      required: true,
      message: "名字不能为空",
      trigger: "change",
    },
  ],
  address: [
    {
      required: true,
      message: "地址不能为空",
      trigger: "change",
    },
  ],
});

const toDealThirdModal = (flag: number) => {
  if (flag === 0) {
    thirdModalTitle.value = "新建酒店";
  } else {
    // 新建文化演艺
    thirdModalTitle.value = "新建文化演艺";
  }

  thirdModalVisible.value = true;
};

const toAddThirdModal = async () => {
  if (thirdModalTitle.value === "新建酒店") {
    let flag = await submitForm(addHotelRef.value);

    if (!flag) return;

    const res = await addHotelAPI(
      addHotelData.value.id,
      addHotelData.value.hotelName,
      addHotelData.value.price,
      addHotelData.value.starLevel.toString(),
      addHotelData.value.position,
      addHotelData.value.region
    );

    if (res.data.code === "200") {
      ElMessage.success("添加成功");

      getAllHotels();
    } else {
      ElMessage.error(res.data.message);
    }

    addHotelData.value = {
      id: null,
      hotelName: "",
      price: 0,
      starLevel: 5,
      position: "",
      region: "",
    };
  } else if (modalSecondTitle.value === "文化演艺") {
    let flag = await submitForm(addCultureRef.value);

    if (!flag) return;

    // let data = addCultureData.value;
    const res = await addArtShowAPI({
      id: addCultureData.value.id,
      name: addCultureData.value.name,
      region: addCultureData.value.region,
      address: addCultureData.value.address,
    });

    if (res.data.code === "200") {
      ElMessage.success("添加成功");

      getAllCulture();
    } else {
      ElMessage.error(res.data.message);
    }

    addCultureData.value = {
      id: null,
      region: "",
      name: "",
      address: "",
    };
  }

  thirdModalVisible.value = false;
};

onMounted(() => {
  getAllRouters();
  // getAllHotels();
});
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.infoBox {
  display: grid;
  grid-auto-columns: 1fr 1fr 1fr;
  gap: 20px;

  display: flex;

  .firstBox,
  .secondBox,
  .thirdBox {
    flex: 1;
  }
}

img {
  width: 120px;
  height: 80px;
}

.el-table__body tr.current-row>td.el-table__cell {
  color: #409eff !important;
  background: #409eff;
}
</style>
